package com.hwg.emp.web.controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.hwg.emp.dto.PageBean;
import com.hwg.emp.service.EmployeeService;
import com.hwg.emp.service.ServiceFactroy;

public class SelectEmpsByConditionController extends HttpServlet{
     @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    	// TODO Auto-generated method stub
    	EmployeeService service = ServiceFactroy.getService(EmployeeService.class);
    	HttpSession session = req.getSession();
    	String con_phone = req.getParameter("con_phone");
    	String page=req.getParameter("page");
      	if(page==null){
  			page="1";
      	}
      	try {
			int e_count = service.selectEmpsCountByCondition(con_phone);
			PageBean pagebean=new PageBean(Integer.parseInt(page),10);
	    	service.selectEmpsByCondition(con_phone, pagebean);
	    	List employees = service.selectEmpsByCondition(con_phone, pagebean);
	    	session.setAttribute("showConEmployees", employees);
  			session.setAttribute("pageList", getPagList(e_count, pagebean.getPage(), pagebean.getPrecord()));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	
    }
     private Object getPagList(int scount, int currentPage, int srecord) {
   		// TODO Auto-generated method stub
   		int totalPage =scount%srecord == 0?scount/srecord:scount/srecord+1;
       	StringBuffer str = new StringBuffer();
       	str.append("<li><a href='selectEmps.do?page=1'>首页</a></li>");
       	if(currentPage==1){
       		str.append("<li class='disabled'><a href='#'>上一页</a></li>");
       	}
       	else{
       		str.append("<li ><a href='selectEmps.do?page="+(currentPage-1)+"'>上一页</a></li>");
       	}
       	for (int i = currentPage-2; i < currentPage+2; i++) {
   			if(i<1||i>totalPage){
   				continue;
   			}
   			if(i==currentPage){
   				str.append("<li class='active'><a href='#'>"+i+"</a></li>");
   			}else{
   				str.append("<li ><a href='selectEmps.do?page="+i+"'>"+i+"</a></li>");
   			}
   		}
       	
       	if(currentPage==totalPage){
       		str.append("<li class='disabled'><a href='#'>下一页</a></li>");
       	}
       	else{
       		str.append("<li ><a href='selectEmps.do?page="+(currentPage+1)+"'>下一页</a></li>");
       	}
       	
       	str.append("<li><a href='selectEmps.do?page="+totalPage+"'>末页</a></li>");
       	return str.toString();
   	}
}
